<script setup lang="ts">

import {onMounted, ref} from "vue";
import {taskImage} from "../store/taskStore.ts";
import html2canvas from "html2canvas";

let ws = ref()
let messageList = ref([])
let sendMessage = ref('')
onMounted(()=>{
  webSocketInit();
})

function handleSendButton() {
  const message = sendMessage.value
  ws.value.send(JSON.stringify({
    message,
    time: new Date().getTime()
  }))
  sendMessage.value = ''
}
function handleLogoutButton(){
  ws.value.close()
  console.log("关闭websocket连接");
  // console.log("关闭连接,重新开始连接");
  // webSocketInit();
}
function handleLoginButton(){
  webSocketInit()
  // console.log("关闭连接,重新开始连接");
  // webSocketInit();
}

function webSocketInit(){
  const webSocketUrl = 'ws://192.168.238.109:8085/trace-server/ws'
  ws.value = new WebSocket(webSocketUrl);
  console.log(ws.value)
  ws.value.onopen = () => {
    console.log("连接成功");
  };
  //后端设置心跳，会每间隔一定时间，触发一次，根据内容变化处理逻辑
  ws.value.onmessage = (e: any) => {
    console.log(e.data, "广播返回的消息");
    //后端约定了，如果返回字符串“UPDATE”，就更新表格
    if (e.data === "UPDATE") {
      //getTable();
    }
  };
  ws.value.onerror = () => {
    console.log("连接错误");
    //断连后每5秒重连一次
    setTimeout(() => {
      initWebSocket();
    }, 5000);
  };

}
</script>

<template>
  <div>
    <table>
      <thead>
      <tr>
        <th>消息编号</th>
        <th>发送者</th>
        <th>发送时间</th>
        <th>发送内容</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="item in messageList" :key="item.time">
        <td>{{ item.id }}</td>
        <td>{{ item.username }}</td>
        <td>{{ new Date(item.time).toLocaleTimeString() }}</td>
        <td>{{ item.message }}</td>
      </tr>
      </tbody>
    </table>
    <input
        type="text"
        v-model="sendMessage"
        placeholder="请输入你要发送的消息">
    <button @click="handleSendButton()">发送</button>
    <button @click="handleLogoutButton()">退出</button>
    <button @click="handleLoginButton()">重新连接</button>

  </div>
</template>

<style scoped>

</style>